<?php

namespace Futures\Controller;
use Think\Controller;
use Common\Model\OptionModel;
/**
 *  代理商客户控制器--客户信息（上下级关系）、佣金明细、客户订单
 */
class AgentCustomerController extends AgentBaseController{

	public function index(){
		//查出所有客户
		$user = M('follow');
		//查询我的所有下级
		$uid = session('AGENT.user_id');
		//$map['_string'] = "((route like '".$uid."') or (route regexp '.*,".$uid."$') or (route regexp '((\d+,)*)".$uid."((,\d+)*)') or (route regexp '.*,".$uid."(,\d+)*'))";
		//$map['_string'] = "(route like '{$uid}') or (route regexp ',{$uid},') or (route regexp '^{$uid},') or (route regexp ',{$uid}$')";
		$map['_string']="find_in_set('$uid',route)";
		//是否经纪人搜索
        if($_REQUEST['status']){
            if($_REQUEST['status']==2){
                $map['is_agent']=array('eq',0);//数据库字段
                $status=2;
            }elseif($_REQUEST['status']==1){
                $map['is_agent']=array('eq',1);
                $status=1;
            }else{
                 $status=-2;
            }
        }else{
             $status=-2;
            }
       	$this->assign('status',$status);
       	$map['mobile'] = array('neq',"" );

		//用户名搜索
        if($_REQUEST['nickname']){
            $nickname=$_REQUEST['nickname'];
            $map['nickname']=array('like',"%".trim($nickname)."%");
            $this->assign('nickname',$nickname,'','trim');
        }
        //电话号码搜索
        if($_REQUEST['mobile']){
            $mobile=$_REQUEST['mobile'];
            $map['mobile']=array('like',"%".trim($mobile)."%");
            $this->assign('mobile',$mobile,'','trim');
        }
        //时间段搜索
        $stime = strtotime($_REQUEST['start_time']);
        $etime = strtotime($_REQUEST['end_time']);
        if($stime){
        	$map['subscribe_time'] = array('egt',$stime);//开始到结束之间的所有内容
        }
        if($etime){
					$end_time = $etime+86400;
        	$map['_string'] = "subscribe_time <=".$end_time." and ((route like '{$uid}') or (route regexp ',{$uid},') or (route regexp '^{$uid},') or (route regexp ',{$uid}$'))";//开始到结束之间的所有内容
        }else{
					$map['_string'] = "(route like '{$uid}') or (route regexp ',{$uid},') or (route regexp '^{$uid},') or (route regexp ',{$uid}$')";
				}
        //所属经纪人搜索
        if($_REQUEST['agent']){
        	$agent=$_REQUEST['agent'];
        	//模糊查询得到经纪人ID
        	$sql['nickname']=array('like',"%".$agent."%");
        	$agent_id = M('Follow')->where($sql)->field('id')->select();
        	//查询搜索的经纪人
        	foreach ($agent_id as $v){
        		$uid = $v['id'];

        		$data = $user->where($map)->order('id desc')->select();
        		//查询所属经纪人
        		foreach ($data as $va){
        			$agent_id = substr($va['route'],strrpos($va['route'],","));  //截取出需要的经纪人id
        			if(",".$uid == $agent_id){
        				$route = $route.','.$va['id'];
        			}
        		}
        	}
        	$routes = ltrim($route,",");

        	$wherestr['id'] = array('in',$routes);
        	$list = $this->lists(M('Follow'),$wherestr,'id desc');
        	$this->assign('agent',$agent,'','trim');
        }

		//判断是否有经纪人查询
		if(!empty($list)){

			//循环遍历取出经纪人
			foreach($list as $k=>$v){
				$agent = substr($v['route'],strrpos($v['route'],","));  //截取出需要的经纪人id
				$agent_id = ltrim($agent,",");    //最终的经纪人ID
				$agent_name = M('follow')->where('id='.$agent_id)->field('nickname')->find();
				$list[$k]['agent'] = $agent_name['nickname'];
				//判断每个用户的级数
		        $routes = explode(',',$v['route']); //分割用户route
		        krsort($routes);
		        $routes = array_values($routes);
		        $routes = array_flip($routes);
		        $list[$k]['level'] = $routes[$uid]+1;  //级数
			}
			$this->assign('data',$list);
		}else{
			$this->assign('subscribe_time',$_REQUEST['subscribe_time']);
			$count      = $user->where($map)->count();// 查询满足要求的总记录数
			$Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
			$show       = $Page->show();// 分页显示输出

			$data = $user->where($map)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
			//循环遍历取出经纪人
			foreach($data as $k=>$v){
				if(!empty($v['route'])){    //判断route值不为空
					$agent = substr($v['route'],strrpos($v['route'],","));  //截取出需要的经纪人id
					$agent_id = ltrim($agent,",");    //最终的经纪人ID
					$agent_name = M('follow')->where('id='.$agent_id)->field('nickname')->find();
					$data[$k]['agent'] = $agent_name['nickname'];
					//判断每个用户的级数
			        $routes = explode(',',$v['route']); //分割用户route
			        krsort($routes);
			        $routes = array_values($routes);
			        $routes = array_flip($routes);
			        $data[$k]['level'] = $routes[$uid]+1;  //级数
				}
			}
			$this->assign('data',$data);
		}
		$this->assign('_page',$show);
		$this->display();
	}

	public function downexecl(){
		Vendor('PHPExcel');
		Vendor('Autoloader');

		$username=I('get.username');
		if($username){
			$wherestr['a.nickname']=$username;
		}
		$state=I('get.state');
		if($state!=2){
			$wherestr['b.status']=$state;
		}
		$start=I('get.start');
		/* if($start){
			$wherestr['b.create_time']=array('egt',strtotime($start));
		}
		$end=I('get.end');
		if($end){
			$wherestr['b.create_time']=array('elt',strtotime($end));
		}
		if($start && $end){
			$wherestr['create_time']=array('BETWEEN',strtotime($start).','.strtotime($end));
		} */

		//时间段搜索
		$stime = strtotime($_REQUEST['start_time']);
		$etime = strtotime($_REQUEST['end_time']);
		if($stime){
			$wherestr['create_time'] = array('egt',$stime);
			$ass['create_time'] = array('egt',$stime);
			$not['create_time'] = array('egt',$stime);
		}
		if($etime){
			$wherestr['_string'] = 'create_time <='.$etime+86400;
			$sql['_string'] = 'create_time <='.$etime+86400;
			$sql['_string'] = 'create_time <='.$etime+86400;
		}
		$user_id = session('AGENT.user_id');
		$model = M('Follow');

		$where['_string'] = "(route like '{$user_id}') or (route regexp ',{$user_id},') or (route regexp '^{$user_id},') or (route regexp ',{$user_id}$')";

		$userData = $model->field('id,openid,nickname,mobile,route')->where($where)->select();
		$userData[] = $model->field('id,openid,nickname,mobile,route')->where('id=' . $user_id)->find();
		/*实例化phpexecl类*/
		$objPHPExcel = new \PHPExcel();
		$objPHPExcel->getActiveSheet()->getStyle('C')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
		$objPHPExcel->setActiveSheetIndex(0)
				//Excel的第一列的名称
				->setCellValue('A1', '用户ID')
				->setCellValue('B1', '姓名')
				->setCellValue('C1', '手机')
				->setCellValue('D1', '佣金(元)')
				->setCellValue('E1', '状态')
				->setCellValue('F1', '分配时间')
				->setCellValue('G1', '创建时间');
		/*遍历数组$userData,组装phpexecl的数据*/
		foreach ($userData as $key => $val) {
			$route = explode(',', $val['route']);
			krsort($route);
			$route = array_values($route);
			$route = array_flip($route);
			$userData[$key]['level'] = $route[$user_id] + 1;  //级数
			$wherestr['a.id']=$val['id'];
			$commissions = $model->field('a.id,a.openid,a.nickname,a.mobile,b.commission as commission,b.status,b.update_time,b.create_time')->alias('a')->join('left join wp_futures_commission b on a.id=b.commission_user_id')->where($wherestr)->select();
//			echo $model->_sql();
			foreach ($commissions as $v) {
				$arr[] = $v;
			}
		}

		/*将数据放在phpexecl表中*/
		foreach ($arr as $k => $val) {
			$num = $k + 2;
			$objPHPExcel->setActiveSheetIndex(0)
					//Excel的第A列，uid是你查出数组的键值，下面以此类推
					->setCellValue('A' . $num, $val['id'])
					->setCellValue('B' . $num, $val['nickname'])
					->setCellValue('C' . $num, $val['mobile'])
					->setCellValue('D' . $num, $val['commission'])
					->setCellValue('E' . $num, $val['status'] == 0 ? "未分配" : "已分配")
					->setCellValue('F' . $num, empty($val['update_time']) ? "" : date('Y-m-d H:i:s', $val['update_time']))
					->setCellValue('G' . $num, empty($val['create_time']) ? "" : date('Y-m-d H:i:s', $val['create_time']));
		}

		/*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
		$objPHPExcel->getActiveSheet()->setTitle('佣金明细');
		$objPHPExcel->setActiveSheetIndex(0);
		$time = date("Y/m/d");
		$head = $time."佣金明细.xls";
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename='.$head.'');
		header('Cache-Control: max-age=0');
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit;

	}
	//佣金管理
	public function voucher(){

		$username=I('get.username');
		if($username){
			$sql['nickname']=array('like',"%".$username."%");
			$user_id = M('Follow')->where($sql)->field('id')->find();
			$wherestring['nickname']=$username;
			$this->assign('wherestring',$wherestring);
		}
		$state=I('get.state');
		if($state!=2){
			$wherestr['status']=$state;
			$this->assign('status',$state);
		}else{
			$this->assign('status',$state);
		}
		$start=I('get.start');

        //时间段搜索
        $stime = strtotime($_REQUEST['start_time']);
        $etime = strtotime($_REQUEST['end_time']);
        if($stime){
        	$wherestr['create_time'] = array('egt',$stime);
        	$ass['create_time'] = array('egt',$stime);
        	$not['create_time'] = array('egt',$stime);
        }
        if($etime){
					$etime = $etime+86400;
        	$wherestr['_string'] = 'create_time <='.$etime;
        	$ass['_string'] = 'create_time <='.$etime;
        	$not['start_time'] = 'create_time <='.$etime;
        }
		//查询我的所有下级
		$uid = session('AGENT.user_id');

		if(!empty($_GET['uid'])){
			$uid = $_GET['uid'];
		}else{
			$uid = session('AGENT.user_id');
		}
		$where['_string'] = "(route like '{$uid}') or (route regexp ',{$uid},') or (route regexp '^{$uid},') or (route regexp ',{$uid}$')";
		$route_data = M('Follow')->where($where)->field('id,route')->select();
		// //查询第一级
        $routes = '';
		foreach ($route_data as $v){
            $routes .= ','.$v['id'];
		}

		$routes = $uid.$routes;
        $routes = trim($routes,',');
		//查询
		if(empty($user_id['id'])){
			$wherestr['commission_user_id'] = array('in',$routes);
		}else{
			//判断是否为自己的所属下级
			if(strpos($routes,$user_id['id'])){
				$wherestr['commission_user_id'] = $user_id['id'];
			}else{
				$this->error('未找到此下级');
			}
		}
		$list = $this->lists(M('FuturesCommission'),$wherestr,'id desc');

		/*佣金统计*/
		//已分配佣金
		$ass['status'] = 1;
		if(empty($user_id['id'])){//判断是否有用户查询
			$ass['commission_user_id'] = array('in',$routes);
		}else{
			$ass['commission_user_id'] = $user_id['id'];
		}
		$Assigned = M('FuturesCommission')->where($ass)->field('status,commission')->select();
		foreach($Assigned as $v){
			$ass_money = $ass_money+$v['commission'];
		}
		$ass_money = round($ass_money,2);
		//未分配佣金
		$not['status'] = 0;
		if(empty($user_id['id'])){//判断是否有用户查询
			$not['commission_user_id'] = array('in',$routes);
		}else{
			$not['commission_user_id'] = $user_id['id'];
		}
		$notAssigned = M('FuturesCommission')->where($not)->field('status,commission')->select();
		foreach($notAssigned as $v){
			$not_money = $not_money+$v['commission'];
		}

		$not_money = round($not_money,2);
		$this->assign('ass_money',$ass_money);		//已分配佣金
		$this->assign('not_money',$not_money);		//未分配佣金
		$this->assign('list',$list);
		$this->display();

	}
	//资金明细
	public function fund(){
		//读取配置
        $s_type = C('MONEY_LOG_TYPE');
        $s_types = array_flip($s_type);
        $this->assign('s_types',$s_types);
		//查出所有客户
		$user = M('futures_fund_record');
		//查询我的所有下级
		$uid = session('AGENT.user_id');
		$map['_string'] = "(route like '{$uid}') or (route regexp ',{$uid},') or (route regexp '^{$uid},') or (route regexp ',{$uid}$')";
		if($_REQUEST['status'] && $_REQUEST['status']!=-2){
			$map['type']=$_REQUEST['status'];
			$status = $_REQUEST['status'];
        }
        else{
             $status=-2;
        }
       $this->assign('status',$status);
		//用户名搜索
        if($_REQUEST['nickname']){
            $nickname=$_REQUEST['nickname'];
            $map['nickname']=array('like',"%".trim($nickname)."%");
            $this->assign('nickname',$nickname,'','trim');
        }
        //电话号码搜索
        if($_REQUEST['mobile']){
            $mobile=$_REQUEST['mobile'];
            $map['mobile']=array('like',"%".trim($mobile)."%");
            $this->assign('mobile',$mobile,'','trim');
        }
        //时间段搜索
        $stime = strtotime($_REQUEST['start_time']);
        $etime = strtotime($_REQUEST['end_time']);
        if($stime){
        	$map['create_time'] = array('egt',$stime);
        }
        if($etime){
        	$etime = $etime+86400;
        	$map['create_time'] = array('elt',$etime);
        }
        if($stime && $etime){
        	$map['create_time'] = array('between',''.$stime.','.$etime.'');
        }
		$count      = $user->where($map)->table('wp_futures_fund_record as a')->join('wp_follow as b On a.user_id=b.id')->count();// 查询满足要求的总记录数
        $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出
		$list = $user->where($map)
		->table('wp_futures_fund_record as a')
		->join('wp_follow as b On a.user_id=b.id')
		->field('b.id,b.route,b.mobile,b.nickname,a.money,a.type,a.create_time')
		->limit($Page->firstRow.','.$Page->listRows)->order('create_time desc')->select();
		//循环遍历取出经纪人
		foreach($list as $k=>$v){
			if(!empty($v['route'])){    //判断route值不为空
				$route[] = $v['route'];  //把route赋为一维数组
				$agent = substr($v['route'],strrpos($v['route'],","));  //截取出需要的经纪人id
				$agent_id[] = ltrim($agent,",");    //最终的经纪人ID
				foreach($agent_id as $vo){
					$agent_name = M('follow')->where('id='.$vo)->field('nickname')->find();
					$list[$k]['agent'] = $agent_name['nickname'];
				}
			}
		}
		$this->assign('list',$list);
		//print_r($data);exit;
		$this->assign('show',$show);
		$this->display();
	}
	 /* 资金明细导出*/
    public function download(){
        $map=array();
                //读取配置
        $s_type = C('MONEY_LOG_TYPE');
        $s_types = array_flip($s_type);
        $this->assign('s_types',$s_types);
        //查询我的所有下级
		$uid = session('AGENT.user_id');
		$map['_string'] = "(route like '{$uid}') or (route regexp ',{$uid},') or (route regexp '^{$uid},') or (route regexp ',{$uid}$')";
        //状态搜索
        if($_REQUEST['status'] && $_REQUEST['status']!=-2){
			$map['type']=$_REQUEST['status'];
			$status = $_REQUEST['status'];
        }
        else{
             $status=-2;
        }
        $this->assign('status',$status);

        //时间段搜索
        $stime = strtotime($_REQUEST['start_time']);
        $etime = strtotime($_REQUEST['end_time']);
    	if($stime){
        	$map['create_time'] = array('egt',$stime);
        }
        if($etime){
        	$etime = $etime+86400;
        	$map['create_time'] = array('elt',$etime);
        }
        if($stime && $etime){
        	$map['create_time'] = array('between',''.$stime.','.$etime.'');
        }
         //用户名搜索

         if($_REQUEST['nickname']){
            $nickname=$_REQUEST['nickname'];
            $follow_name['nickname']=array('like',"%".trim($nickname)."%");
            $user_list=M('follow')->field('id,nickname')->where($follow_name)->select();
            foreach($user_list as $key=>$val){
                $uid.=$val['id'].',';
            }
            $map['user_id']=array('in',trim($uid,','));
            $this->assign('nickname',$nickname,'','trim');
         }
          //电话号码搜索
        if($_REQUEST['mobile']){
            $mobile=$_REQUEST['mobile'];
            $map['mobile']=array('like',"%".trim($mobile)."%");
            $this->assign('mobile',$mobile,'','trim');
        }
        $list=M('futures_fund_record')->where($map)->table('wp_futures_fund_record as a')->join('wp_follow as b On a.user_id=b.id')->field('b.route,b.mobile,b.nickname,a.id,a.user_id,a.money,a.type,a.create_time')->order('create_time desc')->select();
        foreach($list as $k=>$v){
            $where_follow['id']=array('eq',$v['user_id']);//用户名称
            $user_name=M('follow')->where($where_follow)->getField('nickname');//用户名称
            $list[$k]['nickname']=$user_name;
        }
        foreach($list as $k=>$v){
			if(!empty($v['route'])){    //判断route值不为空
				$route[] = $v['route'];  //把route赋为一维数组
				$agent = substr($v['route'],strrpos($v['route'],","));  //截取出需要的经纪人id
				$agent_id[] = ltrim($agent,",");    //最终的经纪人ID
				foreach($agent_id as $vo){
					$agent_name = M('follow')->where('id='.$vo)->field('nickname')->find();
					$list[$k]['agent'] = $agent_name['nickname'];
				}
			}
		}
		$twotime=date("Y-m-d H:i:s");
        $filename=$twotime.'代理商资金明细信息.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $data .= "ID,";
        $data .= "会员编号,";
        $data .= "所属经纪人,";
        $data .= "电话号码,";
        $data .= "客户名称,";
        $data .= "金额,";
        $data .= "类型,";
        $data .= "操作时间,\n";

        if(!empty($list)){
            foreach($list as $k=>$v){
                $data .= $v['id'].",";
                $data .= $v['user_id'].",";
                $data .= $v['agent'].",";
                $data .= $v['mobile'].",";
                $data .= $v['nickname'].",";
                $data .= $v['money'].",";
                switch ($v['type']) {
                    case 1:
                        $type  = '充值';
                        break;
                    case 2:
                        $type  = '提现';
                        break;
                    case 3:
                        $type  = '下单';
                        break;
                    case 4:
                        $type  = '平仓';
                        break;
                    case 5:
                        $type  = '盈利';
                        break;
                    case 6:
                        $type  = '佣金';
                        break;
                    case 7:
                        $type  = '系统操作';
                        break;
                    case 8:
                        $type  = '提现返回';
                        break;
                    default:
                        $type  = '';
                        break;
                }
                $data .= $type.",";
                $data .=date('Y-m-d H:i:s',$v['create_time'])."\t,\n";
            }
            echo  @mb_convert_encoding($data, 'GB2312','utf-8');
            exit;
        }
    }
    /*订单信息*/
    public function order(){
    	$follow = M('follow');
    	//查询我的所有下级
		$uid = session('AGENT.user_id');
		$se_id['_string'] = "(route like '{$uid}') or (route regexp ',{$uid},') or (route regexp '^{$uid},') or (route regexp ',{$uid}$')";
		$sunmer = $follow->where($se_id)->select();
		foreach($sunmer as $key=>$val){
                $s_id.=$val['id'].',';
         	}
        $s_id = $s_id.$uid;
        $map['user_id']=array('in',trim($s_id,','));
		$model = M('futures_order');
    	//涨跌搜索
    	if($_REQUEST['direction']){
            if($_REQUEST['direction']==1){
                $map['direction']=array('eq',1);
                $direction=1;
            }elseif($_REQUEST['direction']==2){
                $map['direction']=array('eq',0);
                $direction=2;
            }elseif($_REQUEST['direction']==3){
            	$map['direction']=array('eq',2);
            	$direction=3;
            }else{
            	$direction=-1;
            }
        }
        else{
            $direction=-1;
        }
        $this->assign('direction',$direction);
        //时间段搜索
        $stime = strtotime($_REQUEST['start_time']);
        $etime = strtotime($_REQUEST['end_time']);
        if($stime){
        	$map['create_time'] = array('egt',$stime);
        }
        if($etime){
					$etime = $etime+86400;
        	$map['_string'] = 'create_time <='.$etime;
        }
        $this->assign('create_time',$_REQUEST['create_time']);
        //用户昵称搜索
         if($_REQUEST['user_name']){
		 	 $user_name=$_REQUEST['user_name'];
		 	$follow_name['nickname']=array('like',"%".trim($user_name)."%");
         	$user_list=M('follow')->field('id,nickname')->where($follow_name)->select();
         	foreach($user_list as $key=>$val){
                $uid.=$val['id'].',';
         	}
         	$map['user_id']=array('in',trim($uid,','));
         	$this->assign('user_name',$user_name,'','trim');
		 }
		  //商品名称搜索
         if($_REQUEST['futures_name']){
		 	 $futures_name=$_REQUEST['futures_name'];
		 	$futures_name_where['name']=array('like',"%".trim($futures_name)."%");
         	$futures_list=M('futures')->field('id,name')->where($futures_name_where)->select();
         	foreach($futures_list as $key=>$val){
                $fuid.=$val['id'].',';
         	}
         	$map['futures_id']=array('in',trim($fuid,','));
         	$this->assign('user_name',$futures_name,'','trim');
		 }
    	//查出数据并分配
    	$count      = $model->where($map)->count();// 查询满足要求的总记录数
        $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出
    	$list = $model->where($map)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
    	foreach($list as $k=>$v){
        	$where_futures['id']=array('eq',$v['futures_id']);
			$futures_name=M('futures')->where($where_futures)->getField('name');//商品名称
			$where_follow['id']=array('eq',$v['user_id']);
			$user_name=M('follow')->where($where_follow)->getField('nickname');//用户名称
			$list[$k]['futures_name']=$futures_name;
			$list[$k]['user_name']=$user_name;
		}
    	$this->assign('list',$list);
    	$this->assign('show',$show);
    	//print_r($list);exit;
    	$this->display();
    }
    /*订单信息导出*/
    public function downorder(){
    	$follow = M('follow');
    	//查询我的所有下级
		$uid = session('AGENT.user_id');
		$se_id['_string'] = "(route like '{$uid}') or (route regexp ',{$uid},') or (route regexp '^{$uid},') or (route regexp ',{$uid}$')";
		$sunmer = $follow->where($se_id)->select();
		foreach($sunmer as $key=>$val){
                $s_id.=$val['id'].',';
         	}
        $s_id = $s_id.$uid;
        $map['user_id']=array('in',trim($s_id,','));
    	$model = M('futures_order');
    	//涨跌搜索
    	if($_REQUEST['direction']){
            if($_REQUEST['direction']==1){
                $map['direction']=array('eq',1);
                $direction=1;
            }elseif($_REQUEST['direction']==2){
                $map['direction']=array('eq',0);
                $direction=2;
            }elseif($_REQUEST['direction']==3){
            	$map['direction']=array('eq',2);
            	$direction=3;
            }else{
            	$direction=-1;
            }
        }
        else{
            $direction=-1;
        }
        $this->assign('direction',$direction);
        //时间段搜索
        $stime = strtotime($_REQUEST['start_time']);
        $etime = strtotime($_REQUEST['end_time']);
        if($stime){
        	$map['create_time'] = array('egt',$stime);
        }
        if($etime){
        	$map['_string'] = 'create_time <='.$etime+86400;
        }
        $this->assign('create_time',$_REQUEST['create_time']);
        //用户昵称搜索
         if($_REQUEST['user_name']){
		 	 $user_name=$_REQUEST['user_name'];
		 	$follow_name['nickname']=array('like',"%".trim($user_name)."%");
         	$user_list=M('follow')->field('id,nickname')->where($follow_name)->select();
         	foreach($user_list as $key=>$val){
                $uid.=$val['id'].',';
         	}
         	$map['user_id']=array('in',trim($uid,','));
         	$this->assign('user_name',$user_name,'','trim');
		 }
		  //商品名称搜索
         if($_REQUEST['futures_name']){
		 	 $futures_name=$_REQUEST['futures_name'];
		 	$futures_name_where['name']=array('like',"%".trim($futures_name)."%");
         	$futures_list=M('futures')->field('id,name')->where($futures_name_where)->select();
         	foreach($futures_list as $key=>$val){
                $fuid.=$val['id'].',';
         	}
         	$map['futures_id']=array('in',trim($fuid,','));
         	$this->assign('user_name',$futures_name,'','trim');
		 }
    	//查出数据并分配
    	$count      = $model->where($map)->count();// 查询满足要求的总记录数
        $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出
    	$list = $model->where($map)->order('id desc')->select();
    	foreach($list as $k=>$v){
        	$where_futures['id']=array('eq',$v['futures_id']);
			$futures_name=M('futures')->where($where_futures)->getField('name');//商品名称
			$where_follow['id']=array('eq',$v['user_id']);
			$user_name=M('follow')->where($where_follow)->getField('nickname');//用户名称
			$list[$k]['futures_name']=$futures_name;
			$list[$k]['user_name']=$user_name;
		}
		$twotime=date("Y-m-d H:i:s");
		$filename=$twotime.'代理商订单信息.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $data .= "ID,";
        $data .= "订单号,";
        $data .= "用户名,";
        $data .= "商品名称,";
        $data .= "单价(元),";
        $data .= "总价(元),";
        $data .= "手数,";
        $data .= "权利金,";
        $data .= "开盘价,";
        $data .= "收盘价,";
        $data .= "方向,";
        $data .= "开始时间,";
        $data .= "结束时间,";
        $data .= "创建时间,\n";
        $i=1;
        if(!empty($list)){
            foreach($list as $k=>$v){
            	$data .= $v['id'].",";
            	$data .= $v['transaction_id']."\t,";
            	$data .= $v['user_name'].",";
            	$data .= $v['futures_name'].",";
            	$data .= $v['unit_price'].",";
            	$data .= $v['total_price'].",";
            	$data .= $v['number'].",";
            	$data .= $v['premium'].",";
            	$data .= $v['open_price'].",";
            	$data .= $v['close_price'].",";
            	switch ($v['direction']) {
                    case 1:
                        $direction  = '涨';
                        break;
                    case 0:
                        $direction  = '跌';
                        break;
                    case 2:
                        $direction  = '平';
                        break;
                    default:
                        $direction  = '';
                        break;

                }
            	$data .= $direction.",";
            	$data .= date('Y-m-d H:i:s',$v['begin_time']).",";
            	$data .= date('Y-m-d H:i:s',$v['end_time']).",";
                $data .=date('Y-m-d H:i:s',$v['create_time'])."\t,\n";
            }
            echo  @mb_convert_encoding($data, 'GB2312','utf-8');
            exit;
        }
    }
	//接收参数,查出数据
	public function searche_get(){
		//合约搜索
		$option=I('get.option');
		if($option){
			$whereOption['name']=array('like','%'.$option.'%');
			$optionData=M('futures_option')->where($whereOption)->select();
			if($optionData){
				foreach($optionData as $op){
					$opt[]=intval($op['id']);
				}
				$searchstr['option_id']=array('in',$opt);
			}
			$this->assign('option',$option);
		}
		//开始时间搜索
		$start_time=I('get.start_time');
		if($start_time){
			$stime=strtotime($start_time);
			$searchstr['start_time']=array('$gte'=>$stime);
			$this->assign('start_time',$start_time);
		}
		//结束时间搜索
		$end_time=I('get.end_time');
		if($end_time){
			$etime=strtotime($end_time);
			$searchstr['start_time']=array('$lte'=>$etime);
			$this->assign('end_time',$end_time);
		}
		//同时查询
		if($start_time && $end_time){
			$etime = $etime+86400;
			$searchstr['start_time']=array('$gte'=>$stime,'$lte'=>$etime);
		}
		//状态搜索
		$status=I('get.status');
		if($status && $status!=-2){
			$searchstr['status']=intval($status);
			$this->assign('status',$status);
		}
		//方向搜索
		$direction=I('get.direction');
		if($direction && $direction!=-2){
			$searchstr['direction']=intval($direction);
			$this->assign('direction',$direction);
		}
		//查出该ID下的所有下级
		$Model=new OptionModel('order');
		$ouyuan_model = new OptionModel('euro_order');			//欧元订单
		ini_set('mongo.long_as_object', 1);
		$uid = session('AGENT.user_id');
		$where['_string'] = "(route like '{$uid}') or (route regexp ',{$uid},') or (route regexp '^{$uid},') or (route regexp ',{$uid}$')";
		$userData=M('follow')->where($where)->select();
		$arr=array();
		foreach($userData as $val){
			$arr[]=$val['id'];
		}
		$searchstr['user_id']=array('in',$arr);
		//当有用户搜索时，覆盖$searchstr['user_id'];
		$name=I('get.name');
		if($name){
			$whereName['nickname']=array('like','%'.$name.'%');
			$nickData=M('follow')->where($whereName)->select();
			$nick=array();
			foreach($nickData as $nic){
				$nick[]=$nic['id'];
			}
			$searchstr['user_id']=array('in',$nick);

			$this->assign('name',$name);
		}

		//当$nickData或者$optionData为空是将$henData置为空
		if(($name && !$nickData) || ($option && !$optionData)){
			$henData=array();
		}else{
			if(ACTION_NAME=='henzhiOrder'){
			$pagesize=$Model->where($searchstr)->count();
			$page=new \Think\Page($pagesize,10);
			$henData=$Model->where($searchstr)->limit($page->firstRow.','.$page->listRows)->order('id desc')->select();
			$this->assign('page',$page);
			}elseif(ACTION_NAME=='ouyuanOrder'){
				$pagesize=$ouyuan_model->where($searchstr)->count();
				$page=new \Think\Page($pagesize,10);
				$henData=$ouyuan_model->where($searchstr)->limit($page->firstRow.','.$page->listRows)->order('id desc')->select();
				$this->assign('page',$page);
			}elseif(ACTION_NAME=='downouyuanorder'){
				$henData=$ouyuan_model->where($searchstr)->order('id desc')->select();
			}elseif(ACTION_NAME=='downhenzhiorder'){
				$henData=$Model->where($searchstr)->order('id desc')->select();
			}
		}
		//组装前台页面需要的数据
		foreach($henData as $key=>$v){
			$usedata=M('follow')->where('id='.$v['user_id'])->find();
			$henData[$key]['nickname']=$usedata['nickname'];
			$optidata=M('futures_option')->where('id='.$v['option_id'])->find();
			$henData[$key]['heyue']=$optidata['name'];
			$henData[$key]['daima']=$optidata['code'];
            $henData[$key]['start_time']=$v['start_time'].'';
            $henData[$key]['end_time']=$v['end_time'].'';
		}
		return $henData;
	}

	public function henzhiOrder(){
		$henData=$this->searche_get();
		$this->assign('henData',$henData);
		$this->display();
	}

	public function downhenzhiorder(){
		$henData=$this->searche_get();
		Vendor('PHPExcel');
		Vendor('Autoloader');
		/*实例化phpexecl类*/
		$objPHPExcel = new \PHPExcel();
//		$objPHPExcel->getActiveSheet()->getStyle('C')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
		$objPHPExcel->setActiveSheetIndex(0)
				//Excel的第一列的名称
				->setCellValue('A1', 'ID')
				->setCellValue('B1', '姓名')
				->setCellValue('C1', '合约')
				->setCellValue('D1', '合约代码')
				->setCellValue('E1', '金额')
				->setCellValue('F1', '当前卖价')
				->setCellValue('G1', '平仓买价')
				->setCellValue('H1', '方向')
				->setCellValue('I1', '盈利')
				->setCellValue('J1', '时长')
				->setCellValue('K1', '收益率')
				->setCellValue('L1', '状态')
				->setCellValue('M1', '开始时间')
				->setCellValue('N1', '结束时间');
		/*将数据放在phpexecl表中*/
		$num=2;
		foreach ($henData as $k => $value) {
			$objPHPExcel->setActiveSheetIndex(0)
					//Excel的第A列，uid是你查出数组的键值，下面以此类推
					->setCellValue('A' . $num, $value['id'])
					->setCellValue('B' . $num, $value['nickname'])
					->setCellValue('C' . $num, $value['heyue'])
					->setCellValue('D' . $num, $value['daima'])
					->setCellValue('E' . $num, $value['invest'] )
					->setCellValue('F' . $num, $value['buy_price'])
					->setCellValue('G' . $num, $value['sell_price'])
					->setCellValue('H' . $num, $value['direction']==1?"看涨":"看跌")
					->setCellValue('I' . $num, $value['profit'])
					->setCellValue('J' . $num, $value['duration'])
					->setCellValue('K' . $num, $value['yield_rate'])
					->setCellValue('L' . $num, $value['status']==1?"进行中":"已结束")
					->setCellValue('M' . $num, date('Y-m-d H:i:s',$value['start_time']))
					->setCellValue('N' . $num, date('Y-m-d H:i:s',$value['end_time']));
			$num++;
		}

		/*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
		$objPHPExcel->getActiveSheet()->setTitle('佣金明细');
		$objPHPExcel->setActiveSheetIndex(0);
		$time = date("Y/m/d");
		$head = $time."佣金明细.xls";
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename='.$head.'');
		header('Cache-Control: max-age=0');
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit;
	}
	public function ouyuanOrder(){
		$ouData=$this->searche_get();
		$this->assign('henData',$ouData);
		$this->display();
	}
	public function downouyuanorder(){
		$henData=$this->searche_get();
		Vendor('PHPExcel');
		Vendor('Autoloader');
		/*实例化phpexecl类*/
		$objPHPExcel = new \PHPExcel();
		//		$objPHPExcel->getActiveSheet()->getStyle('C')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
		$objPHPExcel->setActiveSheetIndex(0)
		//Excel的第一列的名称
		->setCellValue('A1', 'ID')
		->setCellValue('B1', '姓名')
		->setCellValue('C1', '合约')
		->setCellValue('D1', '合约代码')
		->setCellValue('E1', '金额')
		->setCellValue('F1', '当前卖价')
		->setCellValue('G1', '平仓买价')
		->setCellValue('H1', '方向')
		->setCellValue('I1', '盈利')
		->setCellValue('J1', '时长')
		->setCellValue('K1', '收益率')
		->setCellValue('L1', '状态')
		->setCellValue('M1', '开始时间')
		->setCellValue('N1', '结束时间');
		/*将数据放在phpexecl表中*/
		$num=2;
		foreach ($henData as $k => $value) {
			$objPHPExcel->setActiveSheetIndex(0)
			//Excel的第A列，uid是你查出数组的键值，下面以此类推
			->setCellValue('A' . $num, $value['id'])
			->setCellValue('B' . $num, $value['nickname'])
			->setCellValue('C' . $num, $value['heyue'])
			->setCellValue('D' . $num, $value['daima'])
			->setCellValue('E' . $num, $value['invest'] )
			->setCellValue('F' . $num, $value['buy_price'])
			->setCellValue('G' . $num, $value['sell_price'])
			->setCellValue('H' . $num, $value['direction']==1?"看涨":"看跌")
			->setCellValue('I' . $num, $value['profit'])
			->setCellValue('J' . $num, $value['duration'])
			->setCellValue('K' . $num, $value['yield_rate'])
			->setCellValue('L' . $num, $value['status']==1?"进行中":"已结束")
			->setCellValue('M' . $num, date('Y-m-d H:i:s',$value['start_time']))
			->setCellValue('N' . $num, date('Y-m-d H:i:s',$value['end_time']));
			$num++;
		}

		/*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
		$objPHPExcel->getActiveSheet()->setTitle('欧元订单');
		$objPHPExcel->setActiveSheetIndex(0);
		$time = date("Y/m/d");
		$head = $time."欧元订单.xls";
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename='.$head.'');
		header('Cache-Control: max-age=0');
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit;
	}
}
